﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QMSDAL;
using System.Data;

namespace QuaManSys.OuterInfo
{
    public partial class OuterInfoQueryList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitDropDownLists();
            }
        }

        /// <summary>
        /// 初始化下拉框
        /// </summary>
        private void InitDropDownLists()
        {
            InitProNos();   //初始化工程编号
            InitMachineType();  //初始化机型
            InitMachineNos();   //初始化机号
            InitExtraInfo();
        }

        //加载所有机号，默认项为空
        private void InitMachineNos()
        {
            //清空后加载默认项
            ddlMacNos.Items.Clear();
            ListItem defaultItem = new ListItem("----请选择----", "-1");
            ddlMacNos.Items.Add(defaultItem);

            //加载数据库中的数据
            DataSet ds = GCBH.GetAllTF();
            foreach (DataTable dt in ds.Tables)
            {
                for (int culCol = 0; culCol < dt.Columns.Count; culCol++)
                {
                    for (int culRow = 0; culRow < dt.Rows.Count; culRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[culRow][culCol].ToString());
                        ddlMacNos.Items.Add(li);
                    }
                }
            }

        }

        //加载所有机型，默认项为空
        private void InitMachineType()
        {
            //清空后加载默认项
            ddlMacType.Items.Clear();
            ListItem defaultItem = new ListItem("----请选择----", "-1");
            ddlMacType.Items.Add(defaultItem);

            //加载数据库中的数据
            DataSet ds = GCBH.GetAllJX();
            foreach (DataTable dt in ds.Tables)
            {
                for (int culCol = 0; culCol < dt.Columns.Count; culCol++)
                {
                    for (int culRow = 0; culRow < dt.Rows.Count; culRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[culRow][culCol].ToString());
                        ddlMacType.Items.Add(li);
                    }
                }
            }
        }

        //加载所有机号，默认项为空
        private void InitProNos()
        {
            //清空后加载默认项
            ddlProNo.Items.Clear();
            ListItem defaultItem = new ListItem("----请选择----", "-1");
            ddlProNo.Items.Add(defaultItem);

            //加载数据库中的数据
            DataSet ds = GCBH.GetAllProjectNumbers();
            foreach (DataTable dt in ds.Tables)
            {
                for (int culCol = 0; culCol < dt.Columns.Count; culCol++)
                {
                    for (int culRow = 0; culRow < dt.Rows.Count; culRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[culRow][culCol].ToString());
                        ddlProNo.Items.Add(li);
                    }
                }
            }
        }

        private void InitExtraInfo()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var dbOutInfo = from q in context.OuterQualityInfo
                                select q;
                var dbFeedBack = from q in context.OuterQualityInfoFeedback
                                 select q;
                List<string> producerList = new List<string>();
                List<string> customCoList = new List<string>();
                List<string> fbdeptList = new List<string>();
                
                ddlFactory.Items.Clear();
                ddlCustomCo.Items.Clear();
                ddlLblFbdept.Items.Clear();
                ListItem defaultItem = new ListItem("----请选择----", "-1");
                ddlFactory.Items.Add(defaultItem);
                ddlCustomCo.Items.Add(defaultItem);
                ddlLblFbdept.Items.Add(defaultItem);

                //从数据库中选出生产厂家
                foreach (var item in dbOutInfo)
                {
                    if (!producerList.Contains(item.producer))
                    {
                        producerList.Add(item.producer);
                        ListItem it = new ListItem(item.producer);
                        ddlFactory.Items.Add(it);
                    }
                }
                //从数据库中选出顾客公司和反馈单位
                foreach (var item in dbFeedBack)
                {
                    if (!customCoList.Contains(item.customerCompany))
                    {
                        customCoList.Add(item.customerCompany);
                        ListItem it = new ListItem(item.customerCompany);
                        ddlCustomCo.Items.Add(it);
                    }
                    if (!fbdeptList.Contains(item.feedbackUnit))
                    {
                        ListItem it = new ListItem(item.feedbackUnit);
                        ddlLblFbdept.Items.Add(it);
                        fbdeptList.Add(item.feedbackUnit);
                    }
                }


            }
        }

        /// <summary>
        /// 总表查询
        /// </summary>
        /// <returns></returns>
        public List<OuterQualityInfo> GetAllProducts()
        {
            List<OuterQualityInfo> results = new List<OuterQualityInfo>();
            using (var entity = new QuaManSysEntities())
            {
                var queryAll = from q in entity.OuterQualityInfo
                               join o in entity.OuterQualityInfoFeedback 
                               on q.qualityInfoId equals o.qualityInfoId
                               select new {
                                    q,
                                    o.customerCompany,
                                    o.feedbackUnit
                               };
                
                //根据顾客公司筛选
                string customCo = ddlCustomCo.Text;
                if (customCo != "-1")
                    queryAll = from q in queryAll
                               where q.customerCompany == customCo
                               select q;

                //根据顾客公司筛选
                string feedBack = ddlLblFbdept.Text;
                if (feedBack != "-1")
                    queryAll = from q in queryAll
                              where q.feedbackUnit == feedBack
                              select q;

                results = (from p in queryAll
                              select p.q).ToList();
            }
            return Fileter(results);    //按所选条件筛选信息
        }

        /// <summary>
        /// 按条件筛选需要的信息
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        private List<OuterQualityInfo> Fileter(List<OuterQualityInfo> results)
        {
            //根据信息表编号筛选
            string infoId = txtInfoId.Text.Trim();
            if (infoId != "")
                results = (from q in results
                           where q.qualityInfoId == infoId
                           select q).ToList();

            //根据工程编号筛选
            string proNo = ddlProNo.Text;
            if (proNo != "-1")  //-1为默认值
                results = (from q in results
                           where q.projectNo == proNo
                           select q).ToList();

            //根据机型来筛选
            string macType = ddlMacType.Text;
            if (macType != "-1")
            {
                List<OuterQualityInfo> res = new List<OuterQualityInfo>();
                List<string> listNos = GCBH.GetGCBHbyJX(macType);
                foreach (var item in listNos)
                {
                    var query = from q in results
                                where q.projectNo == item
                                select q;
                    res.AddRange(query.ToList());
                }
                results = res;
            }

            //根据机号来筛选
            string macNo = ddlMacNos.Text;
            if (macNo != "-1")
            {
                List<OuterQualityInfo> res = new List<OuterQualityInfo>();
                List<string> listNos = GCBH.GetGCBHbyTF(macNo);
                foreach (var item in listNos)
                {
                    var query = from q in results
                                where q.projectNo == item
                                select q;
                    res.AddRange(query.ToList());
                }
                results = res;
            }

            //根据重要级别来筛选
            string impLevel = ddlImpLev.Text;
            if (impLevel != "")
                results = (from q in results
                           where q.levelOfImportance == impLevel
                           select q).ToList();

            //根据信息表状态筛选
            string infoState = (ddlInfoState.SelectedIndex - 1).ToString();
            if (infoState != "-1")
                results = (from q in results
                           where q.informationCategory == infoState
                           select q).ToList();

            //根据生产厂家筛选
            string producer = ddlFactory.Text;
            if (producer != "-1")
                results = (from q in results
                           where q.producer == producer
                           select q).ToList();

            //将未处理的信息放前面
            results = (from q in results
                       orderby q.projectCategory
                       select q).ToList();

            List<OuterQualityInfo> finalResults = results;
            return finalResults;
        }


        /// <summary>
        /// 部门查询
        /// </summary>
        /// <returns></returns>
        public List<OuterQualityInfo> GetProducts()
        {
            CurUser user = (CurUser)Session["CurUser"];

            List<OuterQualityInfo> all = GetAllProducts();
            List<OuterQualityInfo> ret = new List<OuterQualityInfo>();
            foreach(var item in all)
            {
                List<string> dept = Common.OuterRelatedDeptOperation.QueryOuterRelatedDept(item.qualityInfoId);
                if (dept.Contains(user.department)) ret.Add(item);
            }
            return ret;
        }

        //总表查询
        protected void btnSearchAll_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "2C", "E0");
            if (roleAccess)
            {
                List<OuterQualityInfo> attributes = GetAllProducts();
                lblCount.Text = Convert.ToString(attributes.Count());
                GridView1.DataSource = attributes;
                GridView1.DataBind();
            }
            else
            {
                lblCount.Text = "0";
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }
        //分表查询
        protected void btnSearchByDept_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "2C", "E1");
            if (roleAccess)
            {
                List<OuterQualityInfo> attributes = GetProducts();
                lblCount.Text = Convert.ToString(attributes.Count());
                GridView1.DataSource = attributes;
                GridView1.DataBind();
            }
            else
            {
                lblCount.Text = "0";
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }
    }
}